package bigdata.monitor.binlog.test;

import bigdata.monitor.binlog.entity.MonitorResult;
import bigdata.monitor.binlog.entity.MonitorRule;
import bigdata.monitor.binlog.service.RuleService;
import bigdata.monitor.binlog.utils.*;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@SpringBootTest
public class Test02 {

    @Autowired
    private RuleService ruleService;

    @Test
    public void test01() {
        String cdcJson = "{ \"table\": \"linkman_information\", \"op\": \"u\", \"before\": { \"id\": \"1001\", \"contact_info\": \"12345678\", \"delete_flag\": 0, \"phone\": \"13812345678\" }, \"after\": { \"id\": \"1001\", \"contact_info\": \"0632-12345678\", \"delete_flag\": \"0\", \"phone\": \"13812345678\" } }";
        boolean evaluate = JsonSchemaRuleEvaluator.evaluate(cdcJson, "id:1000-1002");
        System.out.println(evaluate);
    }

    @Test
    public void test02() {
        // linkman_information update binlog debezium json
//        String cdcJson = "{\"source\":{\"version\":\"2.4.0.Final\",\"connector\":\"TiCDC\",\"name\":\"default\",\"ts_ms\":1761897694405,\"snapshot\":\"false\",\"db\":\"customer_service\",\"schema\":\"customer_service\",\"table\":\"lake_company_linkman_information\",\"server_id\":0,\"gtid\":null,\"file\":\"\",\"pos\":0,\"row\":0,\"thread\":0,\"query\":null},\"before\":{\"id\":\"0b737e3867f840948e41acb19c53e570\",\"company_info_id\":\"70cd2fe7f45c4a4cba038ac6695b9c72\",\"linkman_id\":\"5a84a8c28415456d82314d38b33d31d5\",\"contact_type\":\"1\",\"contact_info\":\"15306322000\",\"is_default\":\"1\",\"position_index\":\"1709190272637\",\"delete_flag\":\"0\",\"create_user_id\":\"0000\",\"create_user_name\":\"系统\",\"create_time\":\"2024-11-28 09:53:07\",\"update_user_id\":null,\"update_user_name\":null,\"update_time\":\"2025-09-30 15:35:36\",\"is_color\":\"1\",\"weight_sort\":\"0\",\"update_remark\":\"555\"},\"after\":{\"id\":\"0b737e3867f840948e41acb19c53e570\",\"company_info_id\":\"70cd2fe7f45c4a4cba038ac6695b9c72\",\"linkman_id\":\"5a84a8c28415456d82314d38b33d31d5\",\"contact_type\":\"1\",\"contact_info\":\"1530632200\",\"is_default\":\"1\",\"position_index\":\"1709190272637\",\"delete_flag\":\"0\",\"create_user_id\":\"0000\",\"create_user_name\":\"系统\",\"create_time\":\"2024-11-28 09:53:07\",\"update_user_id\":\"598c54cd3b5d40bdb8c3acfaf08f79c0\",\"update_user_name\":\"四月\",\"update_time\":\"2025-10-31 16:01:34\",\"is_color\":\"1\",\"weight_sort\":\"0\",\"update_remark\":\"555\"},\"op\":\"u\",\"ts_ms\":1761897694405,\"transaction\":null}";
        String cdcJson = "{\"id\": 0, \"database\": \"customer_service\", \"table\": \"lake_company_linkman_information_source\", \"pkNames\": [\"id\"], \"isDdl\": false, \"type\": \"INSERT\", \"es\": 1763080427349, \"ts\": 1763080452139, \"sql\": \"\", \"sqlType\": {\"id\": 12, \"company_info_id\": 12, \"information_id\": 12, \"source_id\": 12, \"delete_flag\": 12, \"create_user_id\": 12, \"create_user_name\": 12, \"create_time\": 12, \"update_user_id\": 12, \"update_user_name\": 12, \"update_time\": 93, \"update_remark\": 12}, \"mysqlType\": {\"id\": \"varchar\", \"company_info_id\": \"varchar\", \"information_id\": \"varchar\", \"source_id\": \"varchar\", \"create_time\": \"varchar\", \"update_user_id\": \"varchar\", \"delete_flag\": \"varchar\", \"create_user_id\": \"varchar\", \"create_user_name\": \"varchar\", \"update_user_name\": \"varchar\", \"update_time\": \"timestamp\", \"update_remark\": \"varchar\"}, \"old\": null, \"data\": [{\"id\": \"000024f8d7e045c89e6bc8bec34a8ae5\", \"company_info_id\": \"test10\", \"information_id\": \"262d35d7d0ec4652b0704b25911b8d52\", \"source_id\": \"contact_info_source_004\", \"delete_flag\": \"1\", \"create_user_id\": \"0000\", \"create_user_name\": \"系统\", \"create_time\": \"2025-11-14 07:46:19\", \"update_user_id\": null, \"update_user_name\": null, \"update_time\": \"2025-11-14 08:35:10\", \"update_remark\": null}]}\n";
//        boolean evaluate = SqliteJsonRuleEvaluator.evaluate(cdcJson, "json_extract(data, '$.after.contact_type') != '1' json_extract(data, '$.before.contact_type')");

        boolean evaluate = SqliteJsonRuleEvaluator.evaluate(cdcJson, "json_extract(data, '$.op') = 'u' AND json_extract(data, '$.after.contact_type') = '1' AND NOT(json_extract(data, '$.after.contact_info') REGEXP '^1[3-9]\\d{9}$')");
        // 宽松模式
//        boolean evaluate = SqliteJsonRuleEvaluator.evaluate(cdcJson, "json_type(json_extract(data, '$.after.delete_flag')) = 'integer'");
        // 严格模式
//        boolean evaluate = SqliteJsonRuleEvaluator.evaluate(cdcJson, "json_type(data, '$.after.delete_flag') = 'integer'");
        System.out.println(evaluate);
    }

    @Test
    public void test03() {
        // information update binlog canal json
//        String binlogJsonMessage = "{\"id\": 0, \"database\": \"customer_service\", \"table\": \"lake_company_linkman_information\", \"pkNames\": [\"id\"], \"isDdl\": false, \"type\": \"UPDATE\", \"es\": 1761897693598, \"ts\": 1761897694405, \"sql\": \"\", \"sqlType\": {\"id\": 12, \"company_info_id\": 12, \"linkman_id\": 12, \"contact_type\": 12, \"contact_info\": 12, \"is_default\": 12, \"position_index\": -5, \"delete_flag\": 12, \"create_user_id\": 12, \"create_user_name\": 12, \"create_time\": 12, \"update_user_id\": 12, \"update_user_name\": 12, \"update_time\": 93, \"is_color\": 12, \"weight_sort\": 4, \"update_remark\": 12}, \"mysqlType\": {\"delete_flag\": \"varchar\", \"create_user_name\": \"varchar\", \"update_time\": \"timestamp\", \"is_color\": \"varchar\", \"is_default\": \"varchar\", \"update_user_id\": \"varchar\", \"update_remark\": \"varchar\", \"id\": \"varchar\", \"update_user_name\": \"varchar\", \"weight_sort\": \"int\", \"create_time\": \"varchar\", \"linkman_id\": \"varchar\", \"contact_type\": \"varchar\", \"contact_info\": \"varchar\", \"position_index\": \"bigint unsigned\", \"create_user_id\": \"varchar\", \"company_info_id\": \"varchar\"}, \"old\": [{\"id\": \"0b737e3867f840948e41acb19c53e570\", \"company_info_id\": \"70cd2fe7f45c4a4cba038ac6695b9c72\", \"linkman_id\": \"5a84a8c28415456d82314d38b33d31d5\", \"contact_type\": \"1\", \"contact_info\": \"15306322000\", \"is_default\": \"1\", \"position_index\": \"1709190272637\", \"delete_flag\": \"0\", \"create_user_id\": \"0000\", \"create_user_name\": \"系统\", \"create_time\": \"2024-11-28 09:53:07\", \"update_user_id\": null, \"update_user_name\": null, \"update_time\": \"2025-09-30 15:35:36\", \"is_color\": \"1\", \"weight_sort\": \"0\", \"update_remark\": \"555\"}], \"data\": [{\"id\": \"0b737e3867f840948e41acb19c53e570\", \"company_info_id\": \"70cd2fe7f45c4a4cba038ac6695b9c72\", \"linkman_id\": \"5a84a8c28415456d82314d38b33d31d5\", \"contact_type\": \"1\", \"contact_info\": \"15306322001\", \"is_default\": \"1\", \"position_index\": \"1709190272637\", \"delete_flag\": \"0\", \"create_user_id\": \"0000\", \"create_user_name\": \"系统\", \"create_time\": \"2024-11-28 09:53:07\", \"update_user_id\": \"598c54cd3b5d40bdb8c3acfaf08f79c0\", \"update_user_name\": \"四月\", \"update_time\": \"2025-10-31 16:01:34\", \"is_color\": \"1\", \"weight_sort\": \"0\", \"update_remark\": \"555\"}]}";
        // information_source create binlog canal
        String binlogJsonMessage = "{\"id\": 0, \"database\": \"customer_service\", \"table\": \"lake_company_linkman_information_tag\", \"pkNames\": [\"id\"], \"isDdl\": false, \"type\": \"INSERT\", \"es\": 1763082198598, \"ts\": 1763082199705, \"sql\": \"\", \"sqlType\": {\"id\": 12, \"company_info_id\": 12, \"information_id\": 12, \"tag_id\": 12, \"delete_flag\": 12, \"create_user_id\": 12, \"create_user_name\": 12, \"create_time\": 12, \"update_user_id\": 12, \"update_user_name\": 12, \"update_time\": 93, \"update_remark\": 12}, \"mysqlType\": {\"information_id\": \"varchar\", \"create_user_id\": \"varchar\", \"create_user_name\": \"varchar\", \"update_time\": \"timestamp\", \"id\": \"varchar\", \"company_info_id\": \"varchar\", \"tag_id\": \"varchar\", \"delete_flag\": \"varchar\", \"create_time\": \"varchar\", \"update_user_id\": \"varchar\", \"update_user_name\": \"varchar\", \"update_remark\": \"varchar\"}, \"old\": null, \"data\": [{\"id\": \"0029f75c4fde4eafbd78ede020950127\", \"company_info_id\": \"10011\", \"information_id\": \"10015\", \"tag_id\": \"b665de547a6240cd98a690fb73ed9091\", \"delete_flag\": \"1\", \"create_user_id\": \"0000\", \"create_user_name\": \"系统\", \"create_time\": \"2025-11-14 08:49:38\", \"update_user_id\": null, \"update_user_name\": null, \"update_time\": \"2025-11-14 08:49:54\", \"update_remark\": null}]}";

        String debeziumJson = CanalToDebeziumConverter.convert(binlogJsonMessage);
        System.out.println(debeziumJson);
        JSONObject obj = JSON.parseObject(debeziumJson);
        JSONObject source = obj.getJSONObject("source");
        String databaseName = source.getString("db");
        String tableName = source.getString("table");
        String key = databaseName + "." + tableName;
        List<MonitorRule> rules = ruleService.getSortedRulesByKey(key);
        String batchId = UUID.randomUUID().toString();
        for (MonitorRule rule : rules) {
            try {
                boolean passed = UnifiedRuleEngine.evaluate(debeziumJson, rule);
                if (passed) {
                    // 4. 规则校验成功 → 生成违规结果

                    // 提取主键值（用于标识哪条记录违规）
                    String primaryKey = JsonUtils.getPrimaryKey(debeziumJson, rule.getPrimaryField());

                    // 根据 output_fields 配置，提取 before/after 的变更字段值
                    String changedFields = JsonPathFieldExtractor.extractChangedFields(debeziumJson, rule.getOutputFields());

                    // 构建违规结果对象
                    MonitorResult result = new MonitorResult();
                    result.setId(IdWorker.getId());
                    result.setDatabaseName(databaseName);
                    result.setTableName(tableName);
                    result.setPrimaryKey(primaryKey);
                    result.setBatchId(batchId); // 用于去重或追踪
                    result.setRuleName(rule.getRuleName());
                    result.setRuleCode(rule.getRuleCode());
                    result.setChangedFields(changedFields); // JSON 字符串，如 {"name":{"before":"A","after":"B"}}
                    result.setCreateTime(LocalDateTime.now());
                    // 序列化为 JSON 并发送到违规事件 Topic
                    String violationJson = JSON.toJSONString(result, JSONWriter.Feature.WriteMapNullValue);
                    System.out.println(violationJson);
                }
            } catch (Exception e) {
                // 单条规则异常不应中断整个消息处理
                System.out.println("Error evaluating rule: " + rule.getRuleName());
                // 继续下一条规则
            }
        }
    }
}
